<template>
  <el-card>
    <!-- <template #header>
      <div class="card-header">
        <h3>用户管理</h3>
      </div>
    </template> -->
    
    <div class="search-input-group">
      <el-form :model="searchForm" :inline="true">
        <el-form-item style="padding:5px" label="用户名">
          <el-input 
            v-model="searchForm.username" 
            placeholder="请输入用户名" 
            clearable
          />
        </el-form-item>
        <el-form-item style="padding:5px" label="状态">
          <el-input 
            v-model="searchForm.status" 
            placeholder="请输入状态" 
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button @click="handleResetSeacrch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="btn-group">
      <el-button 
        v-if="btnGroup.addb" 
        type="primary" 
        :icon="Plus"
        @click="showAddDialog"
      >
        添加
      </el-button>
      <el-button 
        v-if="btnGroup.editb" 
        type="success" 
        :icon="Edit"
        @click="showEditDialog"
        :disabled="multipleSelection.length !== 1"
      >
        修改
      </el-button>
      <el-button 
        v-if="btnGroup.deleteb" 
        type="danger" 
        :icon="Delete"
        @click="handleDelete"
        :disabled="multipleSelection.length <= 0"
      >
        删除
      </el-button>
    </div>
    <el-table 
    :data="dataList" 
    style="width: 100%" 
    row-key="userId"
    @selection-change="handleSelectionChange"
    border
    >
        <el-table-column type="selection" :selectable="selectable" width="40" />
        <!-- <el-table-column prop="userId" label="用户ID" width="80" /> -->
        <el-table-column prop="username" label="用户名"  width="110" show-overflow-tooltip/>
        <el-table-column prop="nickName" label="昵称"  width="130" show-overflow-tooltip/>
        <el-table-column prop="phone" label="手机号"  width="130" show-overflow-tooltip/>
        <el-table-column prop="email" label="邮箱" width="120" show-overflow-tooltip/>
         <!-- <el-table-column prop="avatar" label="信用分" width="70" show-overflow-tooltip/> -->
        <el-table-column prop="creditScore" label="信用分" width="70" show-overflow-tooltip/>
        <el-table-column prop="updateTime" label="更新时间" show-overflow-tooltip />
        <el-table-column prop="createTime" label="创建时间" show-overflow-tooltip />
      </el-table>

      <!-- 分页组件 -->
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        :page-sizes="[10, 20, 50]"
        layout="total, sizes, prev, pager, next"
        background
        @current-change="handleCurrentChange"
        class="pagination"
      />
  </el-card>
  <!-- 添加/修改用户的对话框 -->
  <el-dialog
    :title="dialogTitle"
    v-model="dialogVisible"
    width="500px"
    @close="handleDialogClose"
  >
    <el-form
      :model="operateDataForm"
      :rules="operateDataFormRules"
      ref="operateDataFormRef"
      label-width="80px"
    >
        <el-form-item label="用户名" prop="username">
          <el-input 
            v-model="operateDataForm.username" 
            placeholder="请输入用户名"
            :disabled="isEdit"
          />
        </el-form-item>
      
      <el-form-item label="昵称" prop="nickName">
        <el-input 
          v-model="operateDataForm.nickName" 
          placeholder="请输入昵称"
        />
      </el-form-item>
      
      <el-form-item label="手机号" prop="phone">
        <el-input 
          v-model="operateDataForm.phone" 
          placeholder="请输入手机号"
        />
      </el-form-item>
      
      <el-form-item label="邮箱" prop="email">
        <el-input 
          v-model="operateDataForm.email" 
          placeholder="请输入邮箱"
        />
      </el-form-item>
      
      <el-form-item label="密码" prop="password" v-if="!isEdit">
        <el-input 
          v-model="operateDataForm.password" 
          type="password"
          placeholder="请输入密码"
          show-password
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitUserForm">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup>
import {
    Plus,
    Edit,
    Delete
} from '@element-plus/icons-vue'
import {getUserList,getSearchList,addUser,editUser,deleteUser} from "@/api/management/user"
import { onMounted,reactive,ref,computed } from "vue"
import { useUserStore } from '@/stores/user'

// 模糊查询用户信息
const searchForm=reactive({
  username: '',
  status: ''
})

// 对话框相关数据
const dialogVisible = ref(false)
const isEdit = ref(false)
const operateDataFormRef = ref(null)

// 添加或修改数据表单
const operateDataForm=reactive({
  userId: '',
  username: '',
  nickName: '',
  phone: '',
  email: '',
  password: ''
})

// 表单验证规则
const operateDataFormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ]
}

// 对话框标题
const dialogTitle = computed(() => {
  return isEdit.value ? '修改用户' : '添加用户'
})

// 显示添加用户对话框
const showAddDialog = () => {
  isEdit.value = false
  dialogVisible.value = true
  // 重置表单
  Object.assign(operateDataForm, {
    userId: '',
    username: '',
    nickName: '',
    phone: '',
    email: '',
    password: ''
  })
}

// 显示编辑用户对话框
const showEditDialog = () => {
  isEdit.value = true
  dialogVisible.value = true
  // 填充表单数据
  Object.assign(operateDataForm, multipleSelection.value[0])
}

// 对话框关闭时的处理
const handleDialogClose = () => {
  operateDataFormRef.value.resetFields()
}

// 固定参数源 ---start---
const userStore=useUserStore()
const dataList = ref([])
const multipleSelection=ref([])
const isSerach=ref(false)
const btnGroup=reactive({
    addb:false,
    editb:false,
    deleteb:false
})
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

const getList=()=>{
  let res = getUserList(pagination.currentPage)
  res.then(res=>{
    dataList.value=res.data.records
    let opeStr=res.operateStr
    if(opeStr.includes("*")||opeStr.includes("a")) btnGroup.addb=true
    if(opeStr.includes("*")||opeStr.includes("d")) btnGroup.deleteb=true
    if(opeStr.includes("*")||opeStr.includes("u")) btnGroup.editb=true
    pagination.total=res.data.total
    pagination.pageSize=res.data.size
    pagination.currentPage=res.data.current
  })
}

const handleSearch=()=>{ 
  isSerach.value=true
  let res=getSearchList({...searchForm},pagination.currentPage)
  res.then(res=>{ 
    dataList.value=res.data.records
    pagination.total=res.data.total
    pagination.pageSize=res.data.size
    pagination.currentPage=res.data.current
  })
}

const handleResetSeacrch=()=>{ 
  searchForm.username=""
  searchForm.status=""
  isSerach.value=false
  handleSearch()
}

// 添加或修改数据操作提交
const submitUserForm = () => {
  operateDataFormRef.value.validate(async (valid) => {
    if (valid) {
      if (isEdit.value) await editUser({...operateDataForm});
      else await addUser({...operateDataForm});
      dialogVisible.value = false
      refreshList()
    }
  })
}

// 删除数据操作提交
const handleDelete= async()=>{
  pagination.currentPage=1
  const userIds = multipleSelection.value.map(item => item.userId);
  await deleteUser({list:userIds})
  refreshList()
}
const handleSelectionChange = (selection) => {
  multipleSelection.value = selection
}

// 当前页改变时触发
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  refreshList()
}
// --- end ---

// 判断行是否可选择的函数
const selectable = (row, index) => {
  return row.userId !== userStore.getUserId
}

const refreshList = () => {
  if(isSerach.value) handleSearch()
  else getList()
}

onMounted(()=>{
    getList()
})
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.btn-group {
  margin-bottom: 15px;
}

.btn-group .el-button {
  margin-right: 1px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.search-input-group {
  margin-bottom: 15px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.search-input-group .el-form-item {
  margin-bottom: 0;
  margin-right: 15px;
}
</style>